<?php

namespace App\Http\Controllers\Admin;

use App\Models\UserInfo;
use App\Models\VolunteerApply;
use App\Models\VolunteerPosition;
use App\Models\VolunteerServiceTimeLog;
use App\Validate\VolunteerValidate;
use Illuminate\Support\Facades\DB;

/**
 * 志愿者服务报名信息
 */
class VolunteerApplyController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new VolunteerApply();
        $this->validate = new VolunteerValidate();
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param degree string 教育程度 空表示全部
     * @param intention_id int  服务意向id  多个逗号拼接
     * @param times_id int  服务时间id  多个逗号拼接
     * @param sex int 性别  0 或空 1 男  2 女 
     * @param max_age int 最大年龄 
     * @param mim_age int 最小年龄 
     * @param status tinyint 状态  0 或空 全部 1 通过 2 拒绝 3 待审核
     * @param sort tinyint 排序   1 默认排序  2 服务时长排序
     */
    public function lists()
    {
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);
        $keywords = $this->request->input('keywords', '');
        $status = $this->request->input('status', 0);
        $degree = $this->request->input('degree', 0);
        $intention_id = $this->request->input('intention_id', 0);
        $times_id = $this->request->input('times_id', 0);
        $sex = $this->request->input('sex', 0);
        $max_age = $this->request->input('max_age', '');
        $mim_age = $this->request->input('mim_age', '');
        $sort = $this->request->input('sort', '1');
        $sort = $sort == 2 ? 'volunteer_service_time DESC,id DESC' : 'id DESC'; //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题

        $data = $this->model->lists($keywords, $status, $degree, $intention_id, $times_id, $sex, $mim_age, $max_age, $sort, $limit);
        if (empty($data['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        $data = $this->disPageData($data);
        //增加序号
        foreach ($data['data'] as $key => &$val) {
            $data['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            //$data['data'][$key]['is_expire'] = $val['expire_time'] > date('Y-m-d H:i:s') ? false : true;//是否过期  true  已过期  false  未过期

            $user_info = UserInfo::getWechatField($val['user_id'], ['nickname', 'head_img']);
            $data['data'][$key]['head_img'] = $user_info['head_img'];
            $data['data'][$key]['nickname'] = $user_info['nickname'];

            //删除不需要的数据
            foreach ($val['intention'] as $k => &$v) {
                unset($v['is_del'], $v['change_time'], $v['pivot']);
            }
            foreach ($val['times'] as $k => &$v) {
                unset($v['is_del'], $v['change_time'], $v['pivot']);
            }
        }

        return $this->returnApi(200, '获取成功', true, $data);
    }



    /**
     * 详情
     * @param id int 志愿者id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('volunteer_apply_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);
        if (!$res) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $res->toArray();
        $res['degree_name'] = $this->model->getDegree($res['degree']);
        $res['health_name'] = $this->model->getHealth($res['health']);
        $res['sex_name'] = $this->model->getSex($res['sex']);
        $res['volunteer_service_time'] = UserInfo::where('id', $res['user_id'])->value('volunteer_service_time'); //服务时长
        return $this->returnApi(200, "获取成功", true, $res);
    }



    /**
     * 审核
     * @param id int 志愿者记录id
     * @param status 志愿者状态   1.通过   3.拒绝 
     * @param reason 取消、拒绝原因
     */
    public function check()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('check')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if ($this->request->status == 2 && empty($this->request->reason)) {
            return $this->returnApi(201, '拒绝理由不能为空');
        }

        DB::beginTransaction();
        try {
            $res = $this->model->agreeAndRefused($this->request->id, $this->request->status, $this->request->reason);

            /*消息推送*/
            $msg = $this->request->status == 1 ? '通过' : '拒绝';
            //   $position = VolunteerPosition::where('id' , $res->position_id)->value('name');
            if ($this->request->status == 1) {
                $system_id = $this->systemAdd('志愿者审核' . $msg, $res->user_id, $res->account_id, 20, $this->request->id, '您申请的志愿者,已' . $msg);
            } else {
                $system_id = $this->systemAdd('志愿者审核' . $msg, $res->user_id, $res->account_id, 20, $this->request->id, '您申请的志愿者,已' . $msg . '拒绝理由为：' . $this->request->reason);
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "审核成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 获取服务时长列表
     * @param user_id 用户id
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param start_time   开始时间
     * @param end_time   结束时间
     * @param keywords  筛选内容
     */
    public function serviceTimeList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('service_time_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id =  $this->request->input('user_id');
        $keywords =  $this->request->input('keywords');
        $start_time =  $this->request->input('start_time');
        $end_time =  $this->request->input('end_time');
        $page =  $this->request->input('page', 1);
        $limit =  $this->request->input('limit', 10);
        $volunteerServiceTimeLogModel = new VolunteerServiceTimeLog();
        $res = $volunteerServiceTimeLogModel->lists($user_id, $keywords, $start_time, $end_time, $limit);

        if ($res['data']) {
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 调整用户服务时长
     * @param user_id int 读者证用户id
     * @param service_time int 调整的服务时长   单位分钟
     * @param reason text 调整原因
     */
    public function serviceTimeChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('service_time_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $userInfoModel = new UserInfo();
        $volunteerServiceTimeLogModel = new VolunteerServiceTimeLog();

        $user_id = $this->request->input('user_id');
        $service_time = $this->request->input('service_time');
        $reason = $this->request->input('reason');

        $user_info = $userInfoModel->find($user_id);
        if (empty($user_info)) {
            return $this->returnApi(202, "用户信息获取失败");
        }

        $user_info->volunteer_service_time = $user_info->volunteer_service_time + $service_time;

        $insert_data = [
            'user_id' => $user_id,
            'service_time' => $service_time,
            'intro' => $reason,
            'type' => '管理员手动调整服务时长',
            'manage_id' => request()->manage_id,
        ];

        // 启动事务
        DB::beginTransaction();
        try {
            $user_info->save();
            $volunteerServiceTimeLogModel->add($insert_data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "调整成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, '调整失败');
        }
    }
}
